package com.mindspore.federatedime.util;

import android.os.Environment;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.List;

public class FileUtils {

    public static String rootPath = Environment.getExternalStorageDirectory().getPath() + "/";

    public static File createFile(String fileName) {
        File file = new File(rootPath);
        File txtFile = null;
        if (!file.exists()) {
            file.mkdirs();
        }
        try {
            txtFile = new File(file.getCanonicalPath() + "/" + fileName);
            if (!txtFile.exists()) {
                txtFile.createNewFile();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return txtFile;
    }

    public static boolean writeToTxt(String fileName, List<String> contentList) {
        FileOutputStream fileOutputStream;
        BufferedWriter bufferedWriter;
        File txtFile = createFile(fileName);
        if (txtFile != null) {
            try {
                fileOutputStream = new FileOutputStream(txtFile, true);
                bufferedWriter = new BufferedWriter(new OutputStreamWriter(fileOutputStream));
                for (String content : contentList) {
                    bufferedWriter.write(content+"\r\n");
                }
                bufferedWriter.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return false;
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
            return true;
        } else {
            return false;
        }
    }


}
